package com.wing.cms.tag;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

import com.wing.common.util.ApplicationPath;
import com.wing.common.util.SpringDI;

public class LayoutJsTag extends BodyTagSupport {
	/**
	 * Process the start of this tag.
	 * 
	 * @exception JspException
	 *                if a JSP exception has occurred
	 */
	public int doStartTag() throws JspException {
		return (2);
	}

	/**
	 * Save the associated label from the body content (if any).
	 * 
	 * @exception JspException
	 *                if a JSP exception has occurred
	 */
	public int doAfterBody() throws JspException {
		return (SKIP_BODY);
	}

	/**
	 * Release any acquired resources.
	 */
	public void release() {
		super.release();
	}

	/**
	 * Process the end of this tag.
	 * <p>
	 * Support for indexed property since Struts 1.1
	 * 
	 * @exception JspException
	 *                if a JSP exception has occurred
	 */
	public int doEndTag() throws JspException {
		try {
			
			String isLayout = pageContext.getRequest().getParameter("isLayout");
			if(!"1".equals(isLayout)){
				return (EVAL_PAGE);
			}
			
			String webapp = pageContext.getServletContext().getRealPath("/");
			File cssFile = new File(webapp + File.separator + "resources"
					+ File.separator + "css" + File.separator + "layout.css");
			pageContext.getOut().write("<style>");
			if (cssFile.exists()) {
				  FileReader fr = new FileReader(cssFile);
				  BufferedReader br = new BufferedReader(fr);
				  String s = "";
				  while((s=br.readLine())!=null){
				     pageContext.getOut().write(s);
				  }
				  br.close();
				  fr.close();
			}
			pageContext.getOut().write("</style>");
			
			File jsFile = new File(webapp + File.separator + "resources"
					+ File.separator + "js" + File.separator + "layout.js");
			pageContext.getOut().write("<script>");
			if (jsFile.exists()) {
				  FileReader fr = new FileReader(jsFile);
				  BufferedReader br = new BufferedReader(fr);
				  String s = "";
				  while((s=br.readLine())!=null){
				     pageContext.getOut().write(new String(s.getBytes(), "utf-8"));
				  }
				  br.close();
				  fr.close();
			}
			pageContext.getOut().write("</script>");
		} catch (IOException e) {
			e.printStackTrace();
		}

		return (EVAL_PAGE);
	}
}
